package com.jxj.GUI;

import com.jxj.mapper.mapperUser;
import com.jxj.pojo.studentrunning;
import com.jxj.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;


import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.time.Duration;
import java.time.LocalTime;
import java.util.List;

public class teGUI {
    newmain n1 = new newmain();
    private SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
    mapperUser mapperuser = sqlSession.getMapper(mapperUser.class);
    JButton queryButton = new JButton("查询");
    JButton zuofeiButton = new JButton("作废");
    JButton heiButton = new JButton("加入黑名单");
    JButton cleanButton = new JButton("清零");
    JComboBox<String> dropdown;//下拉框
    JTextField queryField = new JTextField();
    DefaultTableModel model = new DefaultTableModel(
            new Object[]{"学生编号", "姓名", "公里数", "开始时间", "结束时间", "平均配速", "路线", "是否有效", "总违纪次数"}, 0
    ) {
        @Override
        public boolean isCellEditable(int row, int column) {
            return false; // 禁止所有单元格编辑
        }
    };
    JTable table = new JTable(model);

    public void tePanelGUI(JPanel tejpanel) {
        //运动数据管理界面
        JPanel topsearch = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        JLabel shutu = new JLabel("筛选条件:");
        queryField.setPreferredSize(new Dimension(200, 27));
        queryField.setBorder(null);
        n1.changeButton(zuofeiButton);
        n1.changeButton(heiButton);
        n1.changeButton(queryButton);
        n1.changeButton(cleanButton);
        String[] options = {"学号", "路线", "违纪次数"};
        dropdown = new JComboBox<>(options);
        dropdown.setBorder(BorderFactory.createEmptyBorder());
        dropdown.setSelectedIndex(0);
        dropdown.setPrototypeDisplayValue("Thisaaaa");
        topsearch.add(shutu);
        topsearch.add(dropdown);
        topsearch.add(queryField);
        topsearch.add(queryButton);
        topsearch.add(zuofeiButton);
        topsearch.add(heiButton);
        topsearch.add(cleanButton);
        tejpanel.add(topsearch, BorderLayout.NORTH);
        tejpanel.add(table);
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setPreferredSize(new Dimension(1000, 500)); // 设置滚动面板的首选大小
        scrollPane.setViewportView(table);
        tejpanel.add(scrollPane, BorderLayout.CENTER);
        caozuo();
    }

    public void caozuo() {
        //查询
        queryButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                search();
            }
        });
        //作废
        zuofeiButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    int row = table.getSelectedRow();
                    if (row == -1) {
                        JOptionPane.showMessageDialog(
                                null, // 父组件，如果为 null，则弹窗会显示在屏幕中央
                                "当前没有选中任何行", // 提示消息
                                "提示", // 标题
                                JOptionPane.INFORMATION_MESSAGE // 提示类型，这里使用信息类型
                        );
                    } else {
                        zuofei();
                    }
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        //黑名单
        heiButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int row = table.getSelectedRow();
                if (row == -1) {
                    JOptionPane.showMessageDialog(
                            null, // 父组件，如果为 null，则弹窗会显示在屏幕中央
                            "当前没有选中任何行", // 提示消息
                            "提示", // 标题
                            JOptionPane.INFORMATION_MESSAGE // 提示类型，这里使用信息类型
                    );
                } else {
                    try {
                        addhei();
                    } catch (SQLException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        });
        //清零
        cleanButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int row = table.getSelectedRow();
                if (row == -1) {
                    JOptionPane.showMessageDialog(
                            null, // 父组件，如果为 null，则弹窗会显示在屏幕中央
                            "当前没有选中任何行", // 提示消息
                            "提示", // 标题
                            JOptionPane.INFORMATION_MESSAGE // 提示类型，这里使用信息类型
                    );
                } else {
                    try {
                        clean();
                    } catch (SQLException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        });
    }

    private void addhei() throws SQLException {
        int result = showConfirmDeleteDialog4();
        if (result == JOptionPane.YES_OPTION) {
            int row = table.getSelectedRow();
            int click = (int) table.getValueAt(row, 0);
            mapperuser.addheiD(click);
            mapperuser.addheiD(click);
            queryButton.doClick();
        }
    }

    private int showConfirmDeleteDialog4() {
        return JOptionPane.showConfirmDialog(null, "确认加入黑名单？加入后该生校园跑数据将清空并无法录入新数据！", "确认", JOptionPane.YES_NO_OPTION);
    }

    //清除所有运动数据
    private void clean() throws SQLException {
        int result = showConfirmDeleteDialog3();
        if (result == JOptionPane.YES_OPTION) {
            int row = table.getSelectedRow();
            int click = (int) table.getValueAt(row, 0);
            mapperuser.cleand(click);
            mapperuser.cleanu(click);
            queryButton.doClick();
        }
    }

    private int showConfirmDeleteDialog3() {
        return JOptionPane.showConfirmDialog(null, "确认清零该生所有运动数据？操作后无法修复", "确认", JOptionPane.YES_NO_OPTION);
    }

    private void zuofei() throws SQLException {
        int result = showConfirmDeleteDialog2();
        if (result == JOptionPane.YES_OPTION) {
            int row = table.getSelectedRow();
            int click = (int) table.getValueAt(row, 0);
            mapperuser.zuifei(click);
            queryButton.doClick();
        }
    }

    public static int showConfirmDeleteDialog2() {
        // 显示确认删除的对话框，并返回用户的选择
        return JOptionPane.showConfirmDialog(null, "确认作废该条跑步数据？操作后无法修复", "确认作废", JOptionPane.YES_NO_OPTION);
    }


    private void search() {
        String text = queryField.getText();
        List<studentrunning> studentrunningList = mapperuser.getStudentList(text);
        //System.out.println(studentrunningList);
        for (studentrunning student : studentrunningList) {
            System.out.println(student);
            model.addRow(new Object[]{student.getStudent_id(), student.getName(), student.getsKM(), student.getStarttime(), student.getEnftime(), student.getAspeed(), student.getLuxian(), student.getYouxiao(), student.getWeiji()});
        }
        studentrunningList.clear();
    }

    private int luxuan_KM(String luxian, int skm) {
        switch (luxian) {
            case "A":
                skm = 1;
                break;
            case "B":
                skm = 2;
                break;
            case "C":
                skm = 3;
                break;
            case "D":
                skm = 4;
                break;
            case "E":
                skm = 5;
                break;
        }
        return skm;
    }

    private String time_KM(String time1, String time2, int skm) {
        LocalTime time11 = LocalTime.parse(time1);
        LocalTime time22 = LocalTime.parse(time2);
        Duration duration = Duration.between(time11, time22);
        double hours = duration.toMinutes() / 60.0;//换算小时
        // 计算平均配速（每公里所需时间）
        double averagePace = skm / hours;
        String formattedValue = String.format("%.2f", averagePace);
        return formattedValue + "km/h";
    }

    private void newmodel(JTable table) {
        table.setRowHeight(30);
        model = new DefaultTableModel(
                new Object[]{"学生编号", "姓名", "公里数", "开始时间", "结束时间", "平均配速", "路线", "是否有效", "总违纪次数"}, 0
        ) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 禁止所有单元格编辑
            }
        };
        table.setModel(model);
    }
}
